<?php
namespace Org\Util;
class WeiXin{
	
	/* 获取本地的自定义菜单 */
	public function getMenu(){
		
	}
	/* 获取自定义菜单(获取在微信服务器上的) */
	protected function getMenu1(){
		$access_token = self::getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token='.$access_token;
		return file_get_contents($url);
	}

	/* 创建自定义菜单(保存到本地) */
	protected function createMenu(){
		
	}
	
	/* 更新到微信 */
	protected function updateMenu(){
		
	}
	
	/* 删除自定义菜单 */
	protected function deleteMenu(){
		
	}
	
	/* 获取app_id,app_secret */
	private function getWxApp(){
		$app = M('api','wx_')->where("user_id = ".session('user_id'))->cache('wx_app',600)->field('app_id,app_secret')->find();
		return $app;
	}
	
	/* 获取access_token */
	private function getAccessToken(){
		$M = M('access_token','wx_');
		$data = $M->cache('ac_token',600)->where('user_id = '.session('user_id'))->find();
		if(NOW_TIME < $data['end_time']){  //如果数据表里存储的access_token时效未过
			return $data['access_token'];
		}else{
			$app = self::getWxApp();
			$appid = $app['app_id'];
			$appsecret = $app['app_secret'];
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
			$result = json_decode(file_get_contents($url));
			$newField = array('access_token'=>$result->access_token,'end_time'=>NOW_TIME+7200);
			$M->where('user_id = '.session('user_id'))->setField($newField);
			S('ac_token',null);
			return $result->access_token;
		}
	}
}